"""
列表

Version: 0.1
Author: yuwl
Date：2024-1-1
"""

import sys

list1 = [1, 3, 5, 7, 100]
print(list1) # [1, 3, 5, 7, 100]
# 乘号表示列表元素的重复
list2 = ['hello'] * 3
print(list2) # ['hello', 'hello', 'hello']
print(len(list1)) # 5
# 下标（索引）运算
print(list1[0]) # 1
print(list1[4]) # 100
# print(list1[5]) # IndexError: list index out of range
print(list1[-1]) # 100
print(list1[-3]) # 5
# 给元素赋值
list1[2] = 300
print(list1) # [1, 3, 300, 7, 100]
for index in range(len(list1)):
	print(list1[index])
for elem in list1:
	print(elem)
for index, elem in enumerate(list1):
	print(index, elem)


# 添加、移除元素
list1 = [1, 3, 5, 7, 100]
# 添加
list1.append(200)
list1.insert(1, 400)
# 合并两个列表
list1 += [1000, 2000]
print(list1) # [1, 400, 3, 5, 7, 100, 200, 1000, 2000]
print(len(list1)) # 9
# 按条件删除
if 3 in list1:
	list1.remove(3)

if 1234 in list1:
	list1.remove(1234)
print(list1) # [1, 400, 5, 7, 100, 200, 1000, 2000]
# 从指定位置删除元素
list1.pop(0)
list1.pop(len(list1) - 1)
print(list1) # [400, 5, 7, 100, 200, 1000]
# 清空列表
list1.clear()
print(list1) # []

# 切片运算
fruits = ['grape', 'apple', 'strawbery', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
fruits2 = fruits[1:4]
print(fruits2) # ['apple', 'strawbery', 'waxberry']
# 切片复制
fruits3 = fruits[:]
print(fruits3) # ['grape', 'apple', 'strawbery', 'waxberry', 'pitaya', 'pear', 'mango']
fruits4 = fruits[-3:-1]
print(fruits4) # ['pitaya', 'pear']
fruits5 = fruits[1::2]
print(fruits5) # ['apple', 'waxberry', 'pear']
# 切片逆序
fruits6 = fruits[::-1]
print(fruits6) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawbery', 'apple', 'grape']

# 排序
list1 = ['orange', 'apple', 'zoo', 'internation', 'blueberry']
list2 = sorted(list1)
# sorted函数返回排序后的拷贝不修改传入的列表
print(list1) # ['orange', 'apple', 'zoo', 'internation', 'blueberry']
print(list2) # ['apple', 'blueberry', 'internation', 'orange', 'zoo']
list3 = sorted(list1, reverse=True)
print(list3) # ['zoo', 'orange', 'internation', 'blueberry', 'apple']
list4 = sorted(list1, key=len)
print(list4) # ['zoo', 'apple', 'orange', 'blueberry', 'internation']
list1.sort(reverse=True)
print(list1) # ['zoo', 'orange', 'internation', 'blueberry', 'apple']

# 生成式和生成器
f = [x for x in range(1, 10)]
print(f) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
f = [x + y for x in 'ABCDE' for y in '1234567']
print(f) # ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7']

# 用列表的生成表达式语法创建列表容器
# 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
f = [x ** 2 for x in range(1, 1000)]
# 查看对象占用内存的字节数
print(sys.getsizeof(f)) # 8856
print(f)

# 注意下面的代码创建的不是一个列表而是一个生成器对象
# 通过生成器可以获取到数据但它不占用额外的空间存储数据
# 每次需要数据的时候就通过内部运算得到数据（需要花费额外的时间）
f = (x ** 2 for x in range(1, 1000))
# 相比生成式生成器不占用存储数据的空间
print(sys.getsizeof(f)) # 200 
print(f) # <generator object <genexpr> at 0x10091b920>
for val in f:
	print(val)





